var form = layui.form, laydate = layui.laydate, annexList = [], upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id"),
    status = getQueryVariable("status");
layui.use(['tableEdit'], function () {
    var  tableEdit = layui.tableEdit;
    let layer = layui.layer;

    lay('.starttime').each(function(){
        laydate.render({
            elem: this
        });
    });

    //产品明细数据
    let detailList = [];
    //附件明细数据
    //操作日志数据
    let operationLog = [];
    layer.ready(function () {
        //获取详情信息
        $.ajax({
            url:"sellOutStock/detail?id="+id,
            success:function(res){
                if(res.status == 200){
                    //主表信息赋值
                    if(null != res.data){
                        //主表数据
                        let vo =  res.data;
                        form.val("editor-form", {
                            "id" : vo.id,
                            "newBillNo" : vo.billNo,
                            "billNo" : vo.billNo,
                            "time" : vo.time,
                            "carryPlanNo" : vo.carryPlanNo,
                            "customerName" : vo.customerName,
                            "contactPerson" : vo.contactPerson,
                            "contactPersonPhone" : vo.contactPersonPhone,
                            "contactPersonAddress" : vo.contactPersonAddress,
                            "outPerson" : vo.outPerson,
                            "operation" : vo.operation,
                            "pickUpDate" : vo.pickUpDate,
                            "memo" : vo.memo
                        });

                        //产品明细数据
                        if(null != res.data.detailList && res.data.detailList.length > 0){
                            let temp = res.data.detailList;
                            for(let i in temp){
                                let sameId = GenNonDuplicateID(3);
                                temp[i]["sameId"] = sameId;
                                detailList.push(temp[i]);
                            }
                            table.reload('storageproductstableid',{data : detailList});
                        }

                        //附件
                        if(null != res.data.annexList && res.data.annexList.length > 0){
                            annexList = res.data.annexList;
                            table.reload('attachmenttableid',{data : annexList});
                        }

                    }
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    })

    //监听提交
    form.on('submit(form-element)', function (data) {
        let indexsl = 0;
        //产品明细数据
        let storageproductsdata = table.cache["storageproductstableid"];
        $.each(storageproductsdata, function (index, value) {
            if (typeof (storageproductsdata[index]["outStockQuantity"]) == "undefined" || storageproductsdata[index]["outStockQuantity"] == "") {
                layer.msg("产品表第" + (index + 1) + "条出库数量不能为空");
                indexsl++;
                return false;
            }
            if(indexsl > 0){
                return false;
            }
        });

        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        if (indexsl == 0) {
            req["detailList"] = storageproductsdata;

            //获取附件数据
            let annexReqs = table.cache["attachmenttableid"];
            req["annexList"] = annexReqs;
            req["status"] = status;
            let datas = JSON.stringify(req);
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:datas,
                url:"sellOutStock/add",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("保存成功", {icon: 6});
                        setTimeout(function () {
                            //保存成功则刷新提交过来的界面 并关闭此页面
                            parent.detab("views/jsp/WarehouseManagement/salesofoutbound.jsp");
                            parent.intab("views/jsp/WarehouseManagement/salesofoutbound.jsp","销售出库")
                            parent.detab("views/jsp/WarehouseManagement/tpl/newupsalesofoutbound.jsp"+(id==''?'':'?id='+id));
                        },)
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                    return false;
                }
            });
        }
        return false;
    });

    //--入库产品信息
    let initData = [];
    let cols = table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: initData,
        toolbar: '#storageproductstoolbar',
        cols: [[
            {field: 'numbers',width: 50,type:'numbers',title:'序号'},
            {field: 'lotNo', width: 120, title: '批次号', sort: true},
            {field: 'saleContractNo', width: 120, title: '销售合同号', sort: true},
            {field: 'productCode', width: 120, title: '产品编码', sort: true},
            {field: 'specificationCode', width: 120, title: '规格编码', sort: true},
            {field: 'productUnitName', width: 120, title: '产品单位', sort: true},
            {field: 'outStockQuantity', width: 120, title: '出库数量',event: 'outStockQuantity',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'fcUnitPrice', width: 120, title: '销售单价',event: 'fcUnitPrice',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'costSubtotal', width: 120, title: '成本小计',event: 'costSubtotal',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'moneySubtotal', width: 120, title: '金额小计',event: 'moneySubtotal',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'outStockCost', width: 120, title: '出库成本',event: 'outStockCost',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'currency', width: 80, title: '币种', event: 'currency',"config":{"type":"input"}},
            {field: 'shareCostPrice', width: 160, title: '分摊费用单价',event: 'shareCostPrice',"config":{"type":"input","verify":{"type":"number"}}},
            {field: 'trayNumber', width: 120, title: '托盘入数', sort: true},
            {field: 'totalTray', width: 120, title: '总托盘', sort: true},
            {field: 'instoreBillNo', width: 120, title: '入库单号', sort: true},
            {field: 'clientProductNo', width: 120, title: '客户货号', sort: true},
            {field: 'color', width: 120, title: '颜色', sort: true},
            {field: 'productCname', width: 120, title: '中文名称', sort: true},
            {field: 'productEname', width: 120, title: '英文名称', sort: true},
            {field: 'productCdesc', width: 120, title: '中文描述', sort: true},
            {field: 'productEdesc', width: 120, title: '英文描述', sort: true},
            {field: 'specificationExplanation', width: 120, title: '规格说明', sort: true},
            {field: 'grossWeight', width: 120, title: '毛重', sort: true},
            {field: 'grossWeightSubtotal', width: 120, title: '毛重小计', sort: true},
            {field: 'netWeight', width: 120, title: '净重', sort: true},
            {field: 'netWeightSubtotal', width: 120, title: '净重小计', sort: true},
            {field: 'bulk', width: 120, title: '体积', sort: true},
            {field: 'bulkSubtotal', width: 120, title: '体积小计', sort: true},
            {field: 'boxAmount', width: 80, title: '箱数', sort: true},
            {field: 'everyBoxAmount', width: 120, title: '每箱数量', sort: true},
            {field: 'clientContractNo', width: 120, title: '客户合同号', sort: true},
            {fixed: 'right', title: '操作', width: 110, align: 'center', toolbar: '#storageproductseditor'}]],
        page: false,
        limit: Number.MAX_VALUE,
        height: 380
        , done: function (res, curr, count) {
            let patentTableFlag = true;
            for (var i = 0; i < res.data.length; i++) {
                if(!isEmpty(res.data[i]["carryPlanNo"]) && !isEmpty(res.data[i]["customerName"]) && patentTableFlag){
                    //客户名称
                    $("#customerName").val(res.data[i]["customerName"]);
                    //出运计划号
                    $("#carryPlanNo").val(res.data[i]["carryPlanNo"]);
                    patentTableFlag = false;
                }

            }

        }
    }).config.cols;
    let aopTable = tableEdit.aopObj(cols); //获取一个aop对象
    aopTable.on('tool(storageproductstable)', function (obj) {
        let field = $(this).data('field');
        let data = obj.data;
        console.log(obj);
        if (field === 'outStockQuantity') {
            //出库数量不能大于剩余数量
            let theRemainingAmount = data["theRemainingAmount"];
            if(obj.value > theRemainingAmount){
                layer.msg("出库数量不能超过剩余数量", {icon: 5});
                return;
            }
            obj.update({"outStockQuantity": obj.value});
            layer.msg("修改成功", {icon: 6});
        }else if(field === 'fcUnitPrice'){
            obj.update({"fcUnitPrice": obj.value});
            layer.msg("修改成功", {icon: 6});
        }else if(field === 'costSubtotal'){
            obj.update({"costSubtotal": obj.value});
            layer.msg("修改成功", {icon: 6});
        }else if(field === 'moneySubtotal'){
            obj.update({"moneySubtotal": obj.value});
            layer.msg("修改成功", {icon: 6});
        }else if(field === 'outStockCost'){
            obj.update({"outStockCost": obj.value});
            layer.msg("修改成功", {icon: 6});
        }else if(field === 'currency'){
            obj.update({"currency": obj.value});
            layer.msg("修改成功", {icon: 6});
        }else if(field === "shareCostPrice"){
            obj.update({"shareCostPrice":obj.value})
            layer.msg("修改成功", {icon: 6});
        }

        if (obj.event === 'del') {
            layer.confirm('确认删除?',confirmInfo(3,5), function (index) {
                let oldData =  table.cache["storageproductstableid"];
                for(let i in oldData){
                    if(oldData[i].sameId == data.sameId){
                        oldData.splice(i, 1);
                        table.reload('storageproductstableid',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });
        }
    });

    table.on('toolbar(storageproductstable)', function (obj) {
        switch (obj.event) {
            case 'shipmentdetailsinventory':
                layer.open({
                    type: 2,
                    area:["80%","95%"],
                    content: 'views/jsp/WarehouseManagement/tpl/shipmentdetailsinventory.jsp'
                });
                break;
        };
    });

    //---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
        , done: function (res, index, upload) {
            let data = res.data;
            for(let i in data){
                let flag = true;
                for(let j in annexList){
                    if(data[i].id == annexList[j].id){
                        flag = false;
                        break;
                    }
                }
                if(flag){
                    annexList.push(data[i]);
                }
            }
        }
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            let data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        }
        ;
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }
        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    let id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        }
    });

    //---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: operationLog
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }

    //时间处理 初始赋值
    function getNowFormatDate() {
        let date = new Date();
        let separator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }
    let currentDate = getNowFormatDate();
    //出库日期
    laydate.render({
        elem: '#time',
        value: currentDate,
        isInitValue: true
    });

    //生成临时id
    function GenNonDuplicateID(randomLength){
        return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
    }

})